package com.dynabook.ems.aop;

import com.dynabook.ems.annotation.LoginRequired;
import com.dynabook.ems.common.ErrorCode;
import com.dynabook.ems.exception.BusinessException;
import com.dynabook.ems.model.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录校验拦截器
 */
@Aspect
@Component
@Slf4j
@Order(1) // 确保这个拦截器在CookieInterceptor之后执行
public class LoginRequiredInterceptor {

    /**
     * 拦截所有带有@LoginRequired注解的方法
     */
    @Around("@annotation(loginRequired)")
    public Object checkLogin(ProceedingJoinPoint joinPoint, LoginRequired loginRequired) throws Throwable {
        log.debug("执行登录校验拦截");
        
        // 获取请求上下文
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            
            // 从session中获取用户信息
            UserLoginVO userLoginVO = (UserLoginVO) request.getSession().getAttribute("user_login");
            
            // 输出当前用户信息（调试用）
            log.info("当前用户登录信息: {}", userLoginVO);
            
            if (userLoginVO == null) {
                log.error("用户未登录，无法访问需要登录的接口");
                throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "请先登录");
            }
            
            // 检查到用户已登录，继续执行原方法
            return joinPoint.proceed();
        } else {
            log.error("无法获取请求上下文");
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统错误");
        }
    }
} 